<template>
    <view class="page-box">
        <header class="header">
            <view class="bg">
                <image src="http://www.szxlyc.com/uploads/product/20240908/ck2SfcKRftlRjps36F1ovpuhdcNrdAaCcMn5qKkQ.png" mode="widthFix"></image>
            </view>
            <view class="top row verCenter">
                <view class="pic">
                    <image :src="incomeReport.wx_photo" mode="aspectFill"></image>
                </view>
                <text class="tt">{{incomeReport.name}}，很荣幸与您合作</text>
            </view>
            <view style="margin-bottom: 40rpx;" v-if="incomeReport.add_org_time">
                <view class="bar-text">
                    <text class="t1">{{incomeReport.add_org_time.year}}</text>
                    <text class="t2">年</text>
                    <text class="t1">{{incomeReport.add_org_time.month}}</text>
                    <text class="t2">月</text>
                    <text class="t1">{{incomeReport.add_org_time.day}}</text>
                    <text class="t2">日， </text>
                </view>
                <view class="bar-text">
                    <text class="t1">{{incomeReport.invite_name || '黄楠'}}</text>
                    <text class="t2">邀请您加入小朗优创平台</text>
                </view>
                <view class="bar-text">
                    <text class="t2">您与平台已携手</text>
                    <text class="t1">{{incomeReport.add_org_time_days}}</text>
                    <text class="t2">天</text>
                </view>
            </view>
            <view style="margin-bottom: 59rpx;">
                <view class="bar-text">
                    <text class="t2">在您的辛勤付出下，截止今日， </text>
                </view>
                <view class="bar-text">
                    <text class="t2">您已成功促</text>
                    <text class="t1">{{incomeReport.facilitate_customers }}</text>
                    <text class="t2">人</text>
                </view>
                <view class="bar-text">
                    <text class="t2">累计放款</text>
                    <text class="t1">{{incomeReport.grand_credit }}</text>
                    <text class="t2">元</text>
                </view>
                <view class="bar-text">
                    <text class="t2">累计赚取佣金</text>
                    <text class="t3">{{incomeReport.grand_brokerage }}</text>
                    <text class="t2">元</text>
                </view>
            </view>
            <view style="margin-bottom: 59rpx;">
                <view class="bar-text tt column">
                    <text>平台科技赋能，让销售变得更简单， </text>
                    <text>期待您的热忱投入，共创共赢！ </text>
                </view>
            </view>
        </header>
        <view class="btn row bothSide verCenter">
            <view class="btn1 row rowCenter verCenter" @click="open()">发展客户赚佣金</view>
            <view class="btn2 row rowCenter verCenter" @click="open()">组建团队赚津贴</view>
        </view>
        <!-- 弹窗提示 -->
        <uni-popup ref="popup" background-color="#fff" borderRadius="20rpx 20rpx 20rpx 20rpx">
            <view class="popup-content-layer column rowCenter verCenter">
                <view class="content column">
                    <view class="ico">
                        <image src="../../static/chacha.png" mode="aspectFill"></image>
                    </view>
                    <view class="text column rowCenter verCenter">
                        <text class="t1">非常抱歉，您暂时不符合王者级别！ </text>
                        <text class="t2">希望您再接再厉!</text>
                    </view>
                    <view class="tt">您需完成一定任务标准，详情请关注平台最新动态</view>
                    <view class="text-wrap">
                        <view class="title">王者优势：</view>
                        <view class="pp">
                            1、个人做单可享受最高佣金<br />
                            2、下属直接经纪人做单，可享受平台奖励<br />
                            3、优先王者级别经纪人，可享受平台投资开店权限
                        </view>
                    </view>
                </view>
                <view class="iconfont icon-a-tubiaochangyongsousuo9" @click="close()"></view>
            </view>
        </uni-popup>
        <!-- 个人邀请码 -->
        <uni-popup ref="popupInvitationCode" background-color="#fff" borderRadius="20rpx">
            <view class="popup-content column rowCenter verCenter">
                <view class="content column">
                    <template v-if="imageSrc">
                        <image :src="imageSrc" style="width: 686rpx;height: 1120rpx;margin: 0 auto;border-radius: 20rpx;"></image>
                    </template>
                    <template v-else>
                        <canvas id="myCanvas" canvas-id="myCanvas" style="width: 686rpx;height: 1120rpx;margin: 0 auto;opacity: 0;border-radius: 20rpx;"></canvas>
                    </template>
                </view>
                <view class="iconfont icon-a-tubiaochangyongsousuo9" @click="close()"></view>
            </view>
        </uni-popup>
    </view>
</template>

<script>
    import { API } from '@/util/api.js';


    export default {
        data() {
            return {
                incomeReport: {},
                inviteCodePic: '', //邀请的二维码
                imageSrc: '', //canvas生成个人邀请码图片
                info: {} //个人信息
            };
        },
        onShow() {
            this.getData();
        },
        methods: {
            getData() {
                this.request(API.incomeReport, 'GET', {}, true).then(res => {
                    if (res.code === 0) {
                        this.incomeReport = res.data;
                        this.getInvite(); //获取邀请二维码
                    } else {
                        uni.showToast({
                            title: res.msg,
                            icon: 'none'
                        });
                    }
                });
            },
            /**
             * 邀请码弹窗
             */
            invitation() {
                this.$refs.popupInvitationCode.open('center');
                if (!this.imageSrc) {
                    uni.showLoading({
                        mask: true,
                        title: '图片生成中...'
                    });
                    this.$nextTick(() => {
                        setTimeout(() => {
                            this.drawCanvas();
                        }, 800)
                    });
                }
            },
            /**
             * 打开弹窗
             */
            open() {
                this.request(API.getUserInfo, 'GET', {}, true).then(res => {
                    if (res.code === 0) {
                        this.info = res.data;
                        if (res.data.level < 3) {
                            this.$refs.popup.open();
                        } else {
                            this.invitation();
                        }
                    } else {
                        uni.showToast({
                            title: res.msg,
                            icon: 'none'
                        });
                    }
                });


            },
            /**
             * 关闭弹窗
             */
            close() {
                this.$refs.popup.close();
                this.$refs.popupInvitationCode.close();
            },
            /**
             * 获取邀请二维码
             */
            getInvite() {
                this.request(API.invite, 'GET', {}, false).then(res => {
                    if (res.code === 0) {
                        this.inviteCodePic = res.data;
                    } else {
                        uni.showToast({
                            title: res.msg,
                            icon: 'none'
                        });
                    }
                });
            },
            /**
             * 初始化海报
             */
            drawCanvas() {
                console.log('开始绘制图片');
                const query = uni.createSelectorQuery().in(this);

                // 使用exec获取画布的真实宽高
                query.select('#myCanvas').fields({ node: true, size: true }).exec((res) => {
                    if (!res || res.length === 0) {
                        console.error('Failed to get canvas context');
                        return;
                    }

                    // 获取canvas宽高
                    const { width, height } = res[0];

                    // 获取canvas上下文
                    const ctx = uni.createCanvasContext('myCanvas', this);

                    // 使用动态获取的宽高绘制
                    this.drawRoundRect(ctx, 0, 0, width, height, 0, 10);

                    // 绘制背景图
                    this.drawRoundImage(ctx, '../../static/yaoqima.png', 0, 0, width, height, 10);


                    ctx.setFontSize(13);
                    ctx.setFillStyle('#C1CCFF');
                    ctx.font = '13px PingFangSC';
                    const t1 = '更好的车金融产品尽在小朗优创'
                    let t1Width = ctx.measureText(t1).width;
                    ctx.fillText(t1, (width - t1Width) / 2, 58);


                    ctx.setFontSize(14);
                    ctx.setFillStyle('#FFFFFF');
                    ctx.font = 'bold 14px PingFangSC';
                    const t2 = '人无我有，人有我新，人新我专，人专我恒'
                    let t2Width = ctx.measureText(t2).width;
                    ctx.fillText(t2, (width - t2Width) / 2, 88);


                    ctx.setFontSize(13);
                    ctx.setFillStyle('#C1CCFF');
                    ctx.font = '13px PingFangSC';
                    const t3 = '让车抵贷产品和您之间更透明、更体贴'
                    let t3Width = ctx.measureText(t2).width;
                    ctx.fillText(t3, (width - t3Width) / 2, 118);

                    // 绘制白色线条
                    ctx.setFillStyle('rgba(255, 255, 255, 0.1)');
                    const lineWidth = width * 0.85;
                    const lineX = (width - lineWidth) / 2;
                    const lineY = 148;
                    ctx.fillRect(lineX, lineY, lineWidth, 1); // 1px高的线条

                    // 绘制文字部分
                    ctx.setFontSize(11);
                    ctx.setFillStyle('#FFFFFF');
                    ctx.font = '11px PingFangSC';
                    ctx.fillText('运营支持', 30, 180);
                    ctx.setFillStyle('#C1CCFF');
                    ctx.fillText('| 智能匹配系统+人工服务跟进', 80, 180);

                    ctx.setFillStyle('#FFFFFF');
                    ctx.fillText('财务支持', 30, 200);
                    ctx.setFillStyle('#C1CCFF');
                    ctx.fillText('| 佣金快速到账+不跳单不卡佣', 80, 200);

                    ctx.setFillStyle('#FFFFFF');
                    ctx.fillText('产品支持', 30, 220);
                    ctx.setFillStyle('#C1CCFF');
                    ctx.fillText('| 热门贷款产品+明星大咖私人定制服务', 80, 220);

                    // 绘制白色区域 (居中)
                    const rectWidth = 274;
                    const rectHeight = 296;
                    const rectX = (width - rectWidth) / 2;
                    const rectY = 250;
                    this.drawRoundRect(ctx, rectX, rectY, rectWidth, rectHeight, 8);

                    // 头像和用户名在一行水平居中
                    const avatarSize = 44;
                    ctx.setFontSize(14);
                    ctx.setFillStyle('#2E3233');
                    const nameText = this.info.name || '用户名';
                    const nameTextWidth = ctx.measureText(nameText).width;
                    const padding = 10; // 头像和用户名之间的间距

                    // 计算头像和用户名总宽度，并水平居中
                    const totalWidth = avatarSize + padding + nameTextWidth;
                    const startX = (width - totalWidth) / 2;

                    // 绘制头像
                    const avatarX = startX;
                    const avatarY = rectY + 20; // 相对于白色区域的顶部
                    this.drawRoundImage(ctx, this.info.wx_photo_base64, avatarX, avatarY, avatarSize, avatarSize, avatarSize / 2);

                    // 绘制用户名，头像右侧
                    const nameTextX = avatarX + avatarSize + padding;
                    ctx.fillText(nameText, nameTextX, avatarY + avatarSize / 2 + 5);

                    // 二维码区域
                    const qrCodeSize = 170;
                    const qrCodeX = (width - qrCodeSize) / 2;
                    const qrCodeY = avatarY + avatarSize + 10;
                    ctx.drawImage(this.inviteCodePic, qrCodeX, qrCodeY, qrCodeSize, qrCodeSize);

                    // 绘制提示文本
                    ctx.setFontSize(10);
                    ctx.setFillStyle('#6E767A');
                    const t4 = '发展客户，建立团队、轻松玩转车金融';
                    const t4Width = ctx.measureText(t4).width;
                    ctx.fillText(t4, (width - t4Width) / 2, qrCodeY + qrCodeSize + 20);

                    // 画布绘制完成
                    ctx.draw(false, () => {
                        setTimeout(() => {
                            this.convertCanvasToImage();
                        }, 500)
                    });
                });
            },
            drawRoundRect(ctx, x, y, width, height, radius) {
                ctx.setFillStyle('#FFFFFF');
                ctx.beginPath();
                ctx.moveTo(x + radius, y);
                ctx.arcTo(x + width, y, x + width, y + height, radius);
                ctx.arcTo(x + width, y + height, x, y + height, radius);
                ctx.arcTo(x, y + height, x, y, radius);
                ctx.arcTo(x, y, x + width, y, radius);
                ctx.closePath();
                ctx.fill();
            },
            /**
             * 绘制圆角图片
             */
            drawRoundImage(ctx, imagePath, x, y, width, height, radius) {
                ctx.save(); // 保存当前绘图上下文的状态

                // 创建圆角路径
                ctx.beginPath();
                ctx.moveTo(x + radius, y);
                ctx.arcTo(x + width, y, x + width, y + height, radius);
                ctx.arcTo(x + width, y + height, x, y + height, radius);
                ctx.arcTo(x, y + height, x, y, radius);
                ctx.arcTo(x, y, x + width, y, radius);
                ctx.closePath();

                // 裁剪路径
                ctx.clip();

                // 在圆角区域内绘制图片
                ctx.drawImage(imagePath, x, y, width, height);

                ctx.restore(); // 恢复之前保存的绘图上下文的状态
            },
            /**
             * 转图片
             */
            convertCanvasToImage() {
                uni.hideLoading();
                uni.canvasToTempFilePath({
                    canvasId: 'myCanvas',
                    quality: 1,
                    success: (res) => {
                        this.imageSrc = res.tempFilePath;
                        console.log('图片渲染成功');
                    },
                    fail: (error) => {
                        uni.showToast({
                            title: '将画布转换为图片失败',
                            icon: 'none'
                        })
                        console.error('将画布转换为图片失败:', error);
                    }
                }, this);
            }
        }
    };
</script>

<style scoped lang="scss">
    @import '@/assets/css/mine/myIncome.scss';
</style>